<script setup name="maintenanceProjectForm">
import Project from './project.vue'
import { GetListAPI } from '@/api/device/equipment'
import { getDownUserAPI } from '@/api/device/maintenance/workorder.js'
// vue3方法实例
const { proxy } = getCurrentInstance()

const { inspection_item_point_test_mode, inspection_item_inspection_type } = proxy.useDict(
  'inspection_item_inspection_type',
  'inspection_item_point_test_mode'
)

// 子传父
const emit = defineEmits()

// 父传子
const props = defineProps({
  isShow: {
    type: Boolean,
    default: false
  },
  //   传入数据 用于回显
  data: {
    type: Object,
    default: () => {}
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  //   传入数据 弹窗标题
  title: {
    type: String,
    default: '新增'
  }
})

// 标签页字段
const activeName = ref('计划信息')

const ruleFormRef = ref(null)

// 巡检项目弹窗
const projectShow = ref(false)

// 巡检项目勾选数据
const tabelSel = ref([])

// 设备台账列表
const deviceSel = ref([])

// 班组信息列表
const teamSel = ref([])
// 表单字段
const ruleForm = reactive({
  maintenanceProjects: [],

  knowledgeCode: '',
  knowledgeName: '',
  deviceId: '',
  knowledgeFailureType: 0,
  knowledgeFailureDescription: '',
  knowledgeFailurePicture: '',
  knowledgeFailureAnalysis: '',
  knowledgeFailureProcess: ''
})

// 自定义验证
const checkAge = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请填写计划配置项'))
  }
}
// 表单校验
const rules = reactive({
  deviceCode: [{ required: true, message: '请选择设备编号', trigger: 'change' }],
  groupName: [{ required: true, message: '请填写班组', trigger: 'change' }],
  time: [{ required: true, message: '请选择时间', trigger: 'change' }],
  auditOpinion: [{ required: true, message: '请填写审核意见', trigger: 'blur' }]
})

// 添加巡检项目
const addProject = val => {
  ruleForm.maintenanceProjects.push(...val)
  projectShow.value = false
}

// 设备 选择下拉带出相应数据
const deviceCodeChange = val => {
  const result = deviceSel.value.find(item => item.deviceCode == val)
  if (result) {
    ruleForm.deviceName = result.deviceName
    ruleForm.deviceType = result.deviceType
    ruleForm.deviceUnitType = result.deviceUnitType
    ruleForm.installationLocation = result.installationLocationName
    ruleForm.deviceId = result.id
  }
}

// 获取保养人员和保养负责人下拉数据
const getDownUser = async () => {
  const res = await getDownUserAPI()
  ruleForm.maintenanceNumberPeopleOption = res
}
getDownUser()

// 提交方法
const submit = async () => {
  const valid = await ruleFormRef.value.validate()
  if (!valid) return false
  if (ruleForm.time) {
    ruleForm.patrolStartTime = ruleForm.time[0]
    ruleForm.patrolEndTime = ruleForm.time[1]
  }
  return ruleForm
}

// 勾选数据
const handleSelectionChange = rows => {
  tabelSel.value = rows
}
const key = ref(0)
// 计算是否异常
const isYiChang = scope => {
  const val = scope.row
  // 固定值
  if (val.inspectionType == 1) {
    if (val.decisionResultValue == val.decisionResult) {
      ruleForm.patrolItemList[scope.$index].result = 1
    } else {
      ruleForm.patrolItemList[scope.$index].result = 2
    }
  }

  // 状态值
  if (val.inspectionType == 2) {
    if (val.decisionResultValue == 1) {
      ruleForm.patrolItemList[scope.$index].result = 1
    } else {
      ruleForm.patrolItemList[scope.$index].result = 2
    }
  }

  // 范围值
  if (val.inspectionType == 3) {
    const number = Number(val.decisionResultValue)
    const decisionResultOne = Number(val.decisionResult.split(',')[1])
    const decisionResultTwo = Number(val.decisionResult.split(',')[0])
    if (number >= decisionResultTwo && number <= decisionResultOne) {
      ruleForm.patrolItemList[scope.$index].result = 1
    } else {
      ruleForm.patrolItemList[scope.$index].result = 2
    }
  }
}

// 监听回显
const initData = () => {
  if (props.data?.id) {
    Object.keys(props.data).forEach(itemKey => (ruleForm[itemKey] = props.data[itemKey]))
    if (ruleForm.patrolStartTime) ruleForm.time = [ruleForm.patrolStartTime, ruleForm.patrolEndTime]
    ruleForm.patrolItemList = ruleForm.patrolItemList ? ruleForm.patrolItemList : ruleForm.patrolOrderProjectList
    ruleForm.deviceType = props.data.deviceTypeDict
    if (props.title != '派工') {
      ruleForm.maintenanceNumberPeoplea = ruleForm.groupMemberList.map(item => String(item.id))
    }
  }
}

initData()
// 获取设备列表信息
const getDeviceSel = async () => {
  const res = await GetListAPI({ pageNum: 1, pageSize: 9999 })
  deviceSel.value = res.rows
}
getDeviceSel()

const remove = scope => {
  if (tabelSel.value.length > 0) {
    tabelSel.value.forEach(item => {
      const Find = ruleForm.maintenanceProjects.findIndex(itemy => item.id == itemy.id)
      ruleForm.maintenanceProjects.splice(Find, 1)
    })
  } else {
    if (ruleForm.maintenanceProjects?.length < 1) return
    ruleForm.maintenanceProjects.splice(ruleForm.maintenanceProjects.length - 1, 1)
  }
}

// 计算共和
const total = computed(() => {
  let total = 0
  if (Array.isArray(ruleForm.maintenanceProjects) && ruleForm.maintenanceProjects?.length > 0) {
    ruleForm.maintenanceProjects.forEach(item => (total += item.workingHour))
  }
  return total
})
// 导出方法
defineExpose({ submit })
</script>
<template>
  <div class="title">工单信息</div>
  <el-divider />
  <el-form
    inline
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    status-icon
  >
    <el-form-item label="巡检单号" v-if="props.disabled">
      <el-input clearable v-model="ruleForm.inspectionNumber" disabled placeholder="请填写项目名称" />
    </el-form-item>
    <el-form-item label="设备编号" prop="deviceCode">
      <el-select
        :disabled="props.title != '修改' && props.title != '新增'"
        v-model="ruleForm.deviceCode"
        filterable
        placeholder="请选择设备编号"
        @change="deviceCodeChange"
      >
        <el-option v-for="item in deviceSel" :key="item.deviceCode" :label="item.deviceCode" :value="item.deviceCode">
          <span style="float: left">{{ item.deviceName }}</span>
          <span style="float: right; margin-left: 5px; color: var(--el-text-color-secondary); font-size: 13px">{{
            item.deviceCode
          }}</span>
        </el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="设备类型">
      <el-input clearable disabled v-model="ruleForm.deviceType" placeholder="请填写设备类型" />
    </el-form-item>
    <el-form-item label="设备型号">
      <el-input clearable disabled v-model="ruleForm.deviceUnitType" placeholder="请填写设备型号" />
    </el-form-item>
    <el-form-item label="设备名称">
      <el-input clearable v-model="ruleForm.deviceName" disabled placeholder="请填写设备名称" />
    </el-form-item>
    <el-form-item label="位置">
      <el-input clearable v-model="ruleForm.installationLocation" disabled placeholder="请填写位置" />
    </el-form-item>
    <div class="rk" v-if="props.title == '审核'">
      <el-form-item label="审核意见" prop="auditOpinion">
        <el-input type="textarea" clearable v-model="ruleForm.auditOpinion" placeholder="请填写审核意见" />
      </el-form-item>
    </div>
    <!-- 巡检人员 -->
    <div v-if="props.title != '新增'">
      <div class="title">巡检人员</div>
      <el-divider />
      <el-form-item label="班组" prop="groupName">
        <el-input clearable v-model="ruleForm.groupName" :disabled="props.title != '派工' && props.title != '修改'" />
      </el-form-item>
      <el-form-item label="巡检负责人">
        <p-select
          v-model="ruleForm.maintenanceManagerId"
          :disabled="props.title != '派工' && props.title != '修改'"
          :option="ruleForm.maintenanceNumberPeopleOption"
          placeholder="请选择巡检负责人"
        />
      </el-form-item>
      <el-form-item label="巡检人员">
        <p-select
          multiple
          v-model="ruleForm.maintenanceNumberPeoplea"
          :disabled="props.title != '派工' && props.title != '修改'"
          :option="ruleForm.maintenanceNumberPeopleOption"
          placeholder="请选择巡检人员"
        />
      </el-form-item>
    </div>
    <div v-if="props.title == '新增'">
      <div class="title">巡检项目</div>
      <div class="flex-items-center flex-between">
        <div class="title"></div>
        <div class="flex" v-if="!props.disabled">
          <el-tooltip class="box-item" effect="dark" content="添加" placement="top-start">
            <el-icon @click="projectShow = true"><Plus /></el-icon>
          </el-tooltip>
          <div style="margin: 0 10px"></div>
          <el-tooltip class="box-item" effect="dark" content="勾选删除" placement="top-start">
            <el-icon @click="remove"><Minus /></el-icon>
          </el-tooltip>
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        stripe
        border
        :data="ruleForm.maintenanceProjects"
        style="margin-top: 10px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column label="项目编号" prop="patrolItemCode" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="项目名称" prop="patrolItemName" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="巡检内容" prop="patrolItemContent" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="检验标准" prop="patrolItemContent" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="检验类型" prop="inspectionTypeDict" width="auto" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="判定结果项" prop="decisionResult" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="标准工时" prop="workingHour" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="备注" prop="remark" width="auto" align="center" show-overflow-tooltip />
      </el-table>
      <div class="total">
        总工时：
        {{ total }}
      </div>
    </div>

    <!-- 巡检项目 -->
    <div v-if="props.title != '新增' && props.title != '派工'">
      <div class="title">巡检项目</div>
      <el-divider />
      <div class="rk">
        <el-form-item label="巡检起止时间" prop="time">
          <el-date-picker
            clearable
            :disabled="props.title != '执行巡检' && props.title != '修改'"
            v-model="ruleForm.time"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="-"
            type="datetimerange"
            start-placeholder="请选择巡检开始时间"
            end-placeholder="请选择巡检结束时间"
          />
        </el-form-item>
      </div>

      <el-table
        stripe
        border
        :data="ruleForm.patrolItemList"
        style="margin-top: 10px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column label="项目编号" prop="patrolItemCode" width="180" align="center" show-overflow-tooltip />
        <el-table-column label="项目名称" prop="patrolItemName" width="180" align="center" show-overflow-tooltip />
        <!-- <el-table-column label="巡检部位" prop="pointTestPosition" width="auto" align="center" show-overflow-tooltip /> -->
        <!-- <el-table-column label="巡检方式" width="auto" align="center" show-overflow-tooltip>
          <template #default="scope">
            <XiaoheDictTag :options="inspection_item_point_test_mode" :value="scope.row.pointTestMode" />
          </template>
        </el-table-column> -->
        <el-table-column label="巡检内容" prop="patrolItemContent" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="检验标准" prop="inspectionStandard" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="标准工时" prop="workingHour" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="检验类型" prop="inspectionTypeDict" width="auto" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="判定结果项" prop="decisionResult" width="auto" align="center" show-overflow-tooltip />
        <el-table-column label="实际值" prop="remark" width="220" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-input
              @change="isYiChang(scope)"
              v-if="scope.row.inspectionType == 1"
              v-model="scope.row.decisionResultValue"
              :disabled="props.title != '执行巡检' && props.title != '修改'"
            ></el-input>
            <el-radio-group
              @change="isYiChang(scope)"
              v-if="scope.row.inspectionType == 2"
              v-model="scope.row.decisionResultValue"
              :disabled="props.title != '执行巡检' && props.title != '修改'"
            >
              <el-radio label="1" size="large">OK</el-radio>
              <el-radio label="2" size="large">NG</el-radio>
            </el-radio-group>
            <el-input
              :disabled="props.title != '执行巡检' && props.title != '修改'"
              type="number"
              oninput="if(value<=0)value=''"
              v-if="scope.row.inspectionType == 3"
              @blur="isYiChang(scope)"
              v-model="scope.row.decisionResultValue"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="是否异常" prop="maintenanceContent" width="auto" align="center" show-overflow-tooltip>
          <template #default="scope">
            <div :class="scope.row.result == 1 ? 'coloe' : 'red'">{{ scope.row.result == 1 ? '正常' : '异常' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" width="220" align="center" show-overflow-tooltip>
          <template #default="scope">
            <el-input
              clearable
              :disabled="props.title == '查看' || props.title == '审核'"
              v-model="scope.row.remark"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-form>

  <!-- 巡检项目 -->
  <Project :bdb="false" :is-show="projectShow" @preservation="addProject" @cancel="projectShow = false" />
</template>

<style lang="scss" scoped>
.rk ::v-deep .el-form-item {
  width: 100% !important;
}

.rk ::v-deep .el-date-editor {
  width: 40% !important;
}
.title {
  color: #3292fb;
}
.coloe {
  color: #18d26c;
}

.red {
  color: red;
}

.total {
  float: right;
  font-size: 16px;
  margin-top: 15px;
  margin-right: 15px;
}
</style>
